package com.razorthink.shell.commands.essential;

import java.io.File;

import com.razorthink.shell.core.AbstractCommand;
import com.razorthink.shell.core.EnvironmentVariable;
import com.razorthink.shell.utils.CommandLogger;

public class LS extends AbstractCommand {

	public LS(String baseCommand, int params) {
		super(baseCommand, params);
	}

	@Override
	public void execute() {
		if (super.getCommandParser().getParamCount() == 0) {
			EnvironmentVariable v = super.getEnvVar("currentdir");
			if (v == null) {
				String currentdir = getCurrDir();
				listContents(currentdir);
				return;
			} else {
				String currentdir = (String) v.getValue();
				listContents(currentdir);
				return;
			}
		} else {
			String dirPath = super.getCommandParser().getParams().get(0)
					.replace("\\", "/");
			listContents(dirPath);
			return;
		}
	}

	public String getCurrDir() {
		File dir = new File(".");
		if (dir.isDirectory()) {
			return dir.getAbsolutePath();
		} else {
			return dir.getParentFile().getAbsolutePath();
		}
	}

	public void changeDir(String dirPath) {
		super.setEnvVar("currentdir", dirPath);
		String newPrompt = "";
		if (super.getAppContext().getPrompt().contains("@")) {
			String[] arr = super.getAppContext().getPrompt().split("@");
			newPrompt = dirPath + "@" + arr[1];
		} else {
			newPrompt = dirPath + "@" + super.getAppContext().getPrompt();
		}
		super.getAppContext().setPrompt(newPrompt);
		return;
	}

	// public String getCurrentDir() {
	// return System.getProperty("user.dir")
	// + "\\"
	// + System.getProperty("sun.java.command")
	// .substring(
	// 0,
	// System.getProperty("sun.java.command")
	// .lastIndexOf(".")).replace(".", "\\");
	// }

	public void listContents(String dirPath) {
		File dir = new File(dirPath);
		if (!dir.exists()) {
			CommandLogger.logInfo("Directory doesn't exist");
			return;
		}
		if (!dir.isDirectory()) {
			CommandLogger.logInfo("'" + dirPath + "' isn't a directory");
			return;
		}
		File[] list = dir.listFiles();
		for (File f : list) {
			CommandLogger.logInfo("\t" + f.getName());
		}
		CommandLogger.logInfo("# Items: " + list.length);
		changeDir(dirPath);
	}

	@Override
	public String getDescription() {
		return "list the contents of a directory";
	}

	@Override
	public String getUsage() {
		return "ls [directory]";
	}

}
